import axios from 'axios'
import { Message } from 'element-ui'

class HttpRequest {
  constructor(baseURL) {
    this.baseURL = baseURL
    this.instance = axios.create({
      timeout: 50000 // request timeout
    })

    // 请求拦截器
    this.instance.interceptors.request.use(
      config => {
        return config
      },
      error => {
        console.error('Request Interceptor Error:', error)
        return Promise.reject(error)
      }
    )

    // 响应拦截器
    this.instance.interceptors.response.use(
      response => {
        const res = response.data
        if (res.code !== 200) {
          Message({
            message: res.msg || 'Error',
            type: 'error',
            duration: 5 * 1000
          })
          return Promise.reject(new Error(res.message || 'Error'))
        }
        return res
      },
      error => {
        Message({
          message: error.message || 'Request Failed',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(error)
      }
    )
  }

  // 核心请求方法
  request(options) {
    options.baseURL = this.baseURL
    return this.instance(options)
  }

  // GET 请求
  get(url, params = {}, config = {}) {
    return this.request({
      method: 'get',
      url,
      params,
      ...config
    })
  }

  // POST 请求
  post(url, data = {}, config = {}) {
    return this.request({
      method: 'post',
      url,
      data,
      ...config
    })
  }

  // 文件上传
  upload(url, file, fieldName = 'file', extraData = {}, config = {}) {
    const formData = new FormData()
    formData.append(fieldName, file)
    Object.keys(extraData).forEach(key => {
      formData.append(key, extraData[key])
    })

    return this.post(url, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
      ...config
    })
  }
}

export default HttpRequest